<?php

namespace app\controller\admin;

use app\service\ConfServiceFacade;
use laytp\BaseController;
use OSS\Core\OssException;
use OSS\OssClient;
use plugin\ali_oss\service\Oss;
use think\App;
use think\facade\Db;


/**
 * 后台管理员控制器
 */
class Skym extends BaseController
{
    protected $list = [];

    public function __construct(App $app)
    {
        $this->list = [];
        parent::__construct($app);
    }

    function dirList($dir_path = '') {
        if(is_dir($dir_path)) {
            $dirs = opendir($dir_path);
            if($dirs) {
                while(($file = readdir($dirs)) !== false) {
                    if($file !== '.' && $file !== '..') {
                        if(is_dir($file)) {
//                            echo $dir_path . '/' . $file . '<br>';
                            dirList($dir_path . '/' . $file);
                        } else {
                            array_push($this->list,$dir_path . '/' . $file);
//                            echo $dir_path . '/' . $file . '<br>';
                        }
                    }
                }
                closedir($dirs);
            }
        } else {
            echo '目录不存在！';
        }
    }

    public function getSkymJson(){
        $this->dirList("./skym_data/hard");
        foreach ($this->list as $item){
            if(is_file($item)){
                $data = file_get_contents($item);
                $data = json_decode($data,true);
//                if(isset($data['data'])){
//                    $data = $data['data'];
                if(!empty($data['avatar'])){
                    $data['avatar'] = $this->saveImg($this->downloadImage($data['avatar'],"./temp_image/".rand(1,10).".png"),"true","xm_game/skym/music/avatar");
                }
                if(!empty($data['cover'])){
                    $data['cover'] = $this->saveImg($this->downloadImage($data['cover'],"./temp_image/".rand(1,10).".png"),"true","xm_game/skym/music/cover");
                }
                    $insertData = [
                      'name' =>$data['name'],
                      'avatar' =>$data['avatar'],
                      'author' =>$data['author'],
                      'cover' =>$data['cover'],
                      'bpm' =>$data['bpm'],
                      'pitch' =>$data['pitch'],
                      'label_id' =>3,
                      'is_show' =>1,
                      'base_beat' =>$data['baseBeat'],
                      'time_signature' =>$data['timeSignature'],
                      'scale' =>$data['scale'],
                        'notes' =>json_encode($data['notes'],256),
                        'create_time'=>date("Y-m-d H:i:s")
                    ];
                    Db::table("lt_skym_music")->insert($insertData);
                }
//            }
        }
    }

    /**
     * @throws \PhpOffice\PhpSpreadsheet\Exception
     */
    public function saveData(){
        $file = "./temp.xlsx";
        $spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($file);
        $data = [];
        for($i=0;$i<5;$i++){
            $spreadsheet->setActiveSheetIndex($i);
            $sheetData = $spreadsheet->getActiveSheet()->toArray(null, true, true, true);
            unset($sheetData[1]);
            $time = date("Y-m-d H:i:s");
            foreach ($sheetData as $item){
                if(!empty($item['C'])){
                    $data[] =[
                        'bank'=>$item['C'],
                        'province'=>$item['A'],
                        'city'=>$item['B'],
                        'subbranch_bank'=>$item['D'],
                        'create_time'=>$time,
                    ];
                }

            }
        }
        Db::table("lt_system_bank_example")->insertAll($data);
    }


    public function getAuthor(){
        $author = "听风、诉说着幸福、网名:爱之初音、指尖音乐、秋空-旋律、俺是一名音乐老师、指尖旋律演凑谁的忧伤、爱听音乐大师的课、小小音乐盒、俺是音乐歌厅收银员、跳动的音符、听音乐有益身心健康、少男少女音乐俱乐部、剧终丶曲不散、雨の旋律、卡农、美丽的玛瑙河、致爱丽丝、天鹅舞、瞎子阿炳、百鸟朝凤、凤阳花鼓、在希望的田野上、我们走在大路上、学习雷锋好榜样、沂蒙山小调、弹起我心爱的土琵琶、山丹丹花开红艳艳、唱支山歌给党听、映山红、英雄赞歌、歌唱祖国、我爱你中国、热血颂、贝多芬的眼泪、秋日私语、莫斯科没有眼泪、卡农、蓝色多瑙河、贝多芬的月光曲、喀秋莎、夜曲、夜的第七章、致爱丽丝、踏山河、爱的供养、知否、以父之名、风吹麦浪、贝加尔湖畔、假如爱有天意、当我遇到你、不能说的秘密、一路向北、风往北吹、风雨无阻、一路上有你、爱的物语、真爱、伍桢艳、伍雯妞、伍星玉、伍菁芬、伍倩茹、伍景玉、伍秋霞、伍贤琴、伍闵妹、伍星琳、伍芬奇、伍燕洪、伍嘉怡、伍怡秀、伍漫婷、伍雯倩、伍瑞萍、伍珂芳、伍成霞、伍玲秀、伍彩、伍丽莉、伍翔文、伍妍妍、伍红丽、伍志文、伍碧莹、伍艳文、伍音乐、信赖的独奏曲、琴键上的泪、浅夏安然、红尘过客、眉目依旧、一枕清梦、如若安生、酒笙清栀、秋风吟月、落花入盏、林深见鹿、南笙初妤、水墨年华、热爱音乐、悦耳歌声、闻声起舞、音乐余生、乐之符号、优美旋律、此起彼伏、波澜不惊、玄外余音、一曲离殇、曲终人散、爱之初音、指尖.音乐、且听雨吟、心灵的和弦、星空上の音符、秋空、旋律、一个是舞娘、跳动的音符、听·花开的声音、向日葵のMelody、music剧终丶曲不散弦外の余音一曲离殇丶笑看人世繁华秋空、旋律、喜欢听音乐的小蝌蚪、喜欢听音乐的国产车、爱听音乐的玲玲子、喜欢听音乐的网红小玲珑、喜欢听音乐爱吃甜品、魔高一尺爱听音乐的、道高一丈喜欢音乐、喜欢音乐的胖胖、杨枝甘露喜欢音乐、律动发条";
        $author_list = explode("、",$author);
        $this->dirList("./skym_image");
        $count = count($this->list);
        $new_author = [];
        $randNumber=[];
        foreach ($author_list as $item){
            $index = 1;
            while (in_array($index,$randNumber)){
                $index = rand(1,$count);
            }
            array_push($randNumber,$index);
            $new_author[] = [
              'name' =>$item,
                'avatar' => $this->saveImg($this->list[$index], false, "xm_game/skym/music/avatar")
            ];
        }
        Db::table("lt_skym_author")->insertAll($new_author);
    }


    public function saveAuthor(){
        $list =   Db::table("lt_skym_author")->select()->toArray();
        $musicList =   Db::table("lt_skym_music")->where('avatar',"=","")->select()->toArray();
        foreach ($musicList as $item){
            $index = rand(0,134);
            Db::table("lt_skym_music")->where('id',$item['id'])
                ->save([
                   'author'=>$list[$index]['name'],
                   'avatar'=>$list[$index]['avatar'],
                    'cover' => $this->saveImg("./skym_cover/".rand(0,29).".png", false, "xm_game/skym/music/cover"),
                ]);
        }
    }

    public function saveJsonMusic(){
       $list = Db::table("lt_skym_music")->select()->toArray();
       foreach ($list as $item){
           $data = [
               "name" => $item['name'],
               "cover" => "",
               "avatar" => "",
               "author" => "",
               "bpm" => $item['bpm'],
               "pitch" => $item['pitch'],
               "baseBeat" => $item['base_beat'],
               "timeSignature" => $item['time_signature'],
               "scale" => $item['scale'],
               "notes" => json_decode($item['notes'],true),
           ];
           foreach ($data['notes'] as &$i){
               $i['time'] = $i['time']*1;
           }
            switch ($item['label_id']){
                case 1:
                    $file = fopen("./skym_data/easy/".$item['name'].".json","w");
                    fwrite($file,json_encode($data,320));
                    fclose($file);
                    break;
                case 2:
                    $file = fopen("./skym_data/middle/".$item['name'].".json","w");
                    fwrite($file,json_encode($data,320));
                    fclose($file);
                    break;
                case 3:
                    $file = fopen("./skym_data/hard/".$item['name'].".json","w");
                    fwrite($file,json_encode($data,320));
                    fclose($file);
                    break;
            }
       }
    }


    /**
     * 内部人方法将图片保存到阿里云
     * @param $url string 图片地址
     * @param $is_unlink boolean 是否删除
     * @return \think\response\Json|void
     * @throws OssException
     */
    public function saveImg($url, $is_unlink = true, $uploadDir = "xm_game/ah")
    {
        //处理url里面的
        $url = stripslashes($url);
        $url = str_replace("https", "http", $url);
        $list = explode(".", $url);
        $fileExt = $list[count($list) - 1];
        $saveName = date("Ymd") . "/" . md5(uniqid(mt_rand())) . ".{$fileExt}";
        /**
         * 不能以斜杆开头
         *  - 因为OSS存储时，不允许以/开头
         */
//        $uploadDir = "xm_game/ah";
        $object = $uploadDir ? $uploadDir . '/' . $saveName : $saveName;//设置了上传目录的上传文件名
//        $filePath = $object; //保存到lt_files中的path
//        if(ConfServiceFacade::get('system.aliOss.switch') != 1){
//            return $this->error('未开启阿里云OSS存储，请到阿里云OSS配置中开启');
//        }
        //上传至阿里云
        $ossConf = [
            'accessKeyID' => ConfServiceFacade::get('aliOss.accessKeyID'),
            'accessKeySecret' => ConfServiceFacade::get('aliOss.accessKeySecret'),
            'bucket' => ConfServiceFacade::get('aliOss.bucket'),
            'endpoint' => ConfServiceFacade::get('aliOss.endpoint'),
            'domain' => ConfServiceFacade::get('aliOss.domain'),
        ];

        $oss = new OssClient($ossConf['accessKeyID'], $ossConf['accessKeySecret'], $ossConf['endpoint']);
        try {
            $ossUploadRes = $oss->uploadFile($ossConf['bucket'], $object, $url);
            if ($ossUploadRes) {
                if ($is_unlink) {
                    unlink($url);
                }
                if (!isset($ossUploadRes['info']['url'])) {
                    return $this->error('保存失败');
                }
                return $ossUploadRes['info']['url'];
            }
        } catch (OssException $e) {
            return $this->error($e->getMessage());
        }
    }

    public function transferNewSong(){
        $this->dirList("./skym_new_txt/skym2");
        $music = [];
        foreach ($this->list as $index=>$txt){

            $file = fopen($txt,'r');
            $song_notes = [];
            $i = 1;
            $pitch = "";
            $scale = "";
            $name = "";
            $bpm = "";
            while ($data = fgets($file)) {    //每次读取CSV里面的一行内容
                if($i == 1){
                    $title = explode(",",$data);
                    foreach ($title as $key=>$item){
                        if($key==0){
                            $name = explode(".",explode("--",$item)[1])[0];
                        }
                        if($key==1){
                            $bpm = explode("--",$item)[1];
                        }
                        if($key==2){
                            $pitch = explode("--",$item)[1];
                        }
                        if($key==3){
                            $scale = explode("--",$item)[1];
                        }
                    }
                }else{
                    $data= trim($data);
                    $temp = explode(":",$data);
                    $time = "";
                    $nodes = [];
                    foreach ($temp as $key=>$item){
                        if($key==0){
                            $time = trim(explode("--",$item)[1]);
                        }else{
                            $nodes = explode(",",explode("--",$item)[1]);
                        }
                    }
                    foreach ($nodes as $item){
                        $song_notes[] =[
                             'key' => $item,
                             'time' => $time,
                        ];
                    }
                }
                $i++;
            }
            //print_r($song_notes);exit();
            $music[] = [
                'name' =>  $name,
                'bpm' =>  $bpm,
                'pitch' => $pitch ,
                'base_beat' => 8 ,
                'time_signature' => "4/4" ,
                'scale' => $scale ,
                'is_show' => 1 ,
                'notes' =>json_encode($song_notes,JSON_UNESCAPED_UNICODE),
                'create_time'=>date("Y-m-d H:i:s")
            ];
//            echo json_encode($song_notes,JSON_UNESCAPED_UNICODE);
        }
        Db::table("lt_skym_music")->insertAll($music);

    }

    public function transferSong(){
        $this->dirList("./skym_txt");
        $music = [];
        foreach ($this->list as $txt){

            $file = fopen($txt,'r');

            $song_notes = [];
            $duration = 300;
            $startTime = 0;
            while ($data = fgets($file)) {    //每次读取CSV里面的一行内容
                $content = explode('|',$data);
                $ele = [];
                $ele[] = strpos($content[2],'b') === false?$content[2]:'';
                $ele[] = strpos($content[0],'b') === false?$content[0]:'';
                $ele[] = strpos($content[1],'b') === false?$content[1]:'';
                $ele = array_filter($ele);

                if(empty($ele)){
                    $startTime += $duration;
                }else{
                    $eachDuration = $duration/count($ele);
                    if($eachDuration == $duration){
                        $eachDuration = 100;
                    }
                    foreach($ele as $item){
                        if(strpos($item,',')){
                            $all_point = explode(',',$item);
                            foreach($all_point as $point){

                                $song_notes[] = array(
                                    'time' => $startTime,
                                    'key' => str_replace("\n","",str_replace("\"","",$point))
                                );
                            }
                        }else{
                            $song_notes[] = array(
                                'time' => $startTime,
                                'key' => str_replace("\n","",str_replace("\"","",$item))
                            );
                        }

                        $startTime += $eachDuration;
                    }
                }

            }
            //print_r($song_notes);exit();
            $music[] = [
                'name' =>   explode(".",explode("/",$txt)[2])[0],
                'notes' =>json_encode($song_notes,JSON_UNESCAPED_UNICODE),
                'create_time'=>date("Y-m-d H:i:s")
            ];
//            echo json_encode($song_notes,JSON_UNESCAPED_UNICODE);
        }
        Db::table("lt_skym_music")->insertAll($music);

    }

    public function downloadCover(){
        $url = "https://image.baidu.com/search/acjson?tn=resultjson_com&ipn=rj&ct=201326592&is=0%2C0&fp=detail&logid=8427965083904582945&cl=2&lm=-1&ie=utf-8&oe=utf-8&adpicid=0&lpn=0&st=-1&word=%E9%9F%B3%E4%B9%90%E5%A3%81%E7%BA%B8%E6%AF%94%E4%BE%8B1%EF%BC%9A1&z=0&ic=0&hd=0&latest=0&copyright=0&s=undefined&se=&tab=0&width=&height=&face=undefined&istype=2&qc=&nc=&fr=&simics=&srctype=&bdtype=0&rpstart=0&rpnum=0&cs=1644704001%2C1773170136&catename=&nojc=undefined&album_id=&album_tab=&cardserver=&tabname=&pn=0&rn=30&gsm=1e&1673605576496=";
        $result = file_get_contents($url);
        $result = json_decode($result,true);
        foreach ($result['data'] as $key=>$item){
            if($key>29&&isset($item['thumbUrl'])){
                $this->downloadImage($item['thumbURL'],"./skym_cover/".$key.".png");
            }
        }
    }

    //下载图片
    private function downloadImage($url, $filename = './skym_cover/')
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, '0');
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, '0');
        $file = curl_exec($ch);
        curl_close($ch);
        $resource = fopen($filename, 'a');
        fwrite($resource, $file);
        fclose($resource);
        return $filename;
    }
}